package com.gary.spring.nio;

import org.apache.tomcat.util.buf.Utf8Decoder;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;

/**
 * @author peng_rui
 * @date 2022/6/29
 */
public class FileChannelTest {
    public static void main(String[] args) throws Exception {
        //Java.nio.charset.Charset处理了字符转换问题。它通过构造CharsetEncoder和CharsetDecoder将字符序列转换成字节和逆转换。
        Charset charset = StandardCharsets.UTF_8;
        CharsetDecoder decoder = charset.newDecoder();
        //1 创建文件流
        RandomAccessFile accessFile = new RandomAccessFile("D:\\Desk\\whxh\\vpn相关文档\\账户密码.txt", "rw");

        //创建FileChannel
        FileChannel fileChannel = accessFile.getChannel();

        //创建buffer
        ByteBuffer buf = ByteBuffer.allocate(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        int read = fileChannel.read(buf);

        while (read != -1) {
            System.out.println("读取 : " + read);
            buf.flip();
            decoder.decode(buf, charBuffer, false);
            charBuffer.flip();
            while (charBuffer.hasRemaining()) {
                System.out.print(charBuffer.get());
            }
            buf.clear();
            charBuffer.clear();
            read = fileChannel.read(buf);
        }
        fileChannel.close();
        System.out.println("end");
    }
}
